package com.gs.netty.core.dispatch;



import com.gs.netty.core.handler.HandlerExecutionChain;
import com.gs.netty.core.handler.HandlerMapping;
import com.gs.netty.core.handler.adapter.HandlerAdapter;
import com.gs.netty.core.resolver.HandlerExceptionResolver;
import com.gs.netty.core.resolver.HandlerMethodReturnValueHandler;
import org.springframework.beans.factory.InitializingBean;

import java.util.ArrayList;
import java.util.List;
public abstract class FrameworkDispatch<Request,Response> implements Dispatch<Request,Response> , InitializingBean {



    @Override
    public void dispatch(Request request, Response response) {

        doDispatch(request, response);
    }


    public abstract void doDispatch(Request request,Response response);

    /**
     * 处理映射器
     */
    protected List<HandlerMapping> handlerMappings = new ArrayList<>();
    /**
     * 程序处理适配器
     */
    protected List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    /**
     * 异常处理器
     */
    protected List<HandlerExceptionResolver> handlerExceptionResolvers = new ArrayList<>();

    /**
     * 结果处理器
     */
    protected List<HandlerMethodReturnValueHandler> handlerMethodReturnValueHandlers = new ArrayList<>();

    /**
     *
     * @param request
     * @return
     * @throws Exception
     */
    protected HandlerExecutionChain getHandlerInternal(Request request) throws Exception {

        for (HandlerMapping handlerMapping : handlerMappings) {

            if (!handlerMapping.support(request)) {
                continue;
            }
            // 找到处理器
            return handlerMapping.getHandler(request);
        }

        return null;
    }


    public List<HandlerMapping> dispatch() {
        for (HandlerMapping handlerMapping : handlerMappings) {

        }
        return handlerMappings;
    }

    /**
     * 初始化程序
     */
    protected abstract void initHandler();


    protected abstract void noHandlerFound(Request request, Response response);

    @Override
    public void afterPropertiesSet() throws Exception {
        initHandler();
    }
}
